import { defineStore } from "pinia";
import common_util from "@/util/common_util.js";

export const usePermissionService = defineStore("permissionService", {
  state: () => ({
    userList: [],
    // 新增：使用 Map 缓存角色ID -> 权限集合的映射
    rolePermissionsMap: new Map(),
    allPermissions: new Set(),
  }),
  getters: {
    /**
     * 新增：根据角色ID从缓存中获取权限集合
     * @param {object} state
     * @returns {function(number): Set<string>}
     */
    getPermissionsByRoleId: (state) => (roleId) => {
      return state.rolePermissionsMap.get(roleId) || new Set();
    },
  },
  actions: {
    getPermissionList(userId) {
      return new Promise((resolve, reject) => {
        common_util.get("/api/permission/user/full", { userId }, (res) => {
          console.log(res);
          resolve(res);
        });
      });
    },
    /**
     * 新增：批量获取并缓存所有核心角色的权限
     */
    // async cacheAllRolePermissions() {
    //   // 如果已缓存，则不重复执行
    //   if (this.rolePermissionsMap.size > 0) return;

    //   const roleIdsToFetch = [1, 2, 3]; // 1:管理员, 2:导师, 3:学员
    //   try {
    //     // 调用已有的批量接口
    //     const resultMap = await this.batchGetRolePermissions(roleIdsToFetch);
    //     // 将后端返回的普通对象转换为 Map 并存储
    //     this.rolePermissionsMap = new Map(Object.entries(resultMap).map(([key, value]) => [Number(key), new Set(value)]));
    //   } catch (error) {
    //     console.error("缓存角色权限失败:", error);
    //   }
    // },
    // 获取特定用户权限
    /**
     * 新增：批量获取并缓存所有核心角色的权限
     */
    async cacheAllRolePermissions() {
      // 如果已缓存，则不重复执行
      //if (this.rolePermissionsMap.size > 0) return;

      const roleIdsToFetch = [1, 2, 3]; // 1:管理员, 2:导师, 3:学员
      try {
        // 1. 调用接口，返回的值直接就是我们需要的权限数据对象
        const permissionData = await this.batchGetRolePermissions(roleIdsToFetch);
        // console.log("permissionData",permissionData);
        // // 2. 关键修改：直接使用返回的 permissionData 对象构建 Map
        // this.rolePermissionsMap = new Map(Object.entries(permissionData).map(([key, value]) => [Number(key), new Set(value)]));
        // console.log("this.rolePermissionsMap",this.rolePermissionsMap); // 打印缓存的权限数据，用于调试和验证
        this.rolePermissionsMap.clear();

        // 2. 遍历新获取的数据，逐一添加到 Map 中
        for (const [key, value] of Object.entries(permissionData)) {
          this.rolePermissionsMap.set(Number(key), new Set(value));
        }
      } catch (error) {
        console.error("缓存角色权限失败:", error);
      }
    },
    getUsePermission(targetUserId) {
      return new Promise((resolve, reject) => {
        common_util.get(
          "/api/permission/user/list",
          { targetUserId },
          (res) => {
            console.log(res);
            resolve(res);
          },
        );
      });
    },
    /**
     * @description (5) 查询指定角色的权限列表
     * @param {number} roleId - 角色ID
     * @returns {Promise<Set<string>>} 权限描述集合
     */
    getRolePermissions(roleId) {
      return new Promise((resolve, reject) => {
        common_util.get("/api/permission/role/list", { roleId }, (res) => {
          resolve(res);
        }, (error) => reject(error));
      });
    },

    /**
     * @description (6) 批量查询多个角色的权限映射
     * @param {Set<number> | Array<number>} roleIds - 角色ID集合
     * @returns {Promise<Map<number, Set<string>>>} 角色ID到权限描述集合的映射
     */
    batchGetRolePermissions(roleIds) {
      // Set/Array 最终都会被序列化为JSON数组
      return new Promise((resolve, reject) => {
        common_util.post("/api/permission/role/batch", Array.from(roleIds), {}, (res) => {
          resolve(res);
        }, (error) => reject(error));
      });
    },

    /**
     * @description (7) 全量更新指定角色的权限
     * @param {number} roleId - 角色ID
     * @param {Set<string> | Array<string>} permissionDescriptions - 权限描述的全量集合
     * @returns {Promise<string>} 成功消息
     */
    updateRolePermissions(roleId, permissionDescriptions) {
      return new Promise((resolve, reject) => {
        common_util.put("/api/permission/role/update", Array.from(permissionDescriptions), { roleId }, (res) => {
          resolve(res);
        }, (error) => reject(error));
      });
    },

    /**
     * @description (8) 分配单个权限到指定角色
     * @param {number} roleId - 角色ID
     * @param {string} description - 要分配的权限描述
     * @returns {Promise<string>} 成功消息
     */
    assignPermissionToRole(roleId, description) {
      return new Promise((resolve, reject) => {
        common_util.post("/api/permission/role/assign", {}, { roleId, description }, (res) => {
          resolve(res);
        }, (error) => reject(error));
      });
    },

    /**
     * @description (9) 刷新指定角色的权限缓存
     * @param {number} roleId - 角色ID
     * @returns {Promise<string>} 成功消息
     */
    refreshRoleCache(roleId) {
      return new Promise((resolve, reject) => {
        common_util.post("/api/permission/role/refresh-cache", {}, { roleId }, (res) => {
          resolve(res);
        }, (error) => reject(error));
      });
    },
    addUserPermission(targetUserId, description) {
      return new Promise((resolve, reject) => {
        common_util.post(
          "/api/permission/user/add",
          {},
          { targetUserId, description },
          (res) => {
            console.log(res);
            resolve(res);
          },
        );
      });
    },
    deleteUserPermission(targetUserId, description) {
      return new Promise((resolve, reject) => {
        common_util.delete(
          "/api/permission/user/remove",
          {
            targetUserId,
            description,
          },
          (res) => {
            console.log("成功删除权限");
            resolve(res);
          },
          (error) => {
            console.error("删除权限失败:", error);
            reject(error);
          },
        );
      });
    },
    getUserList() {
      return new Promise((resolve) => {
        common_util.get("/api/user/list", {}, (res) => {
          console.log(res);
          // 将API返回的数据转换为表格需要的格式
          const formattedUsers = res.map((user) => ({
            id: user.id,
            username: user.name,
            role: this.mapRoleIdToName(user.roleId),
            status: this.mapStageToStatus(user.stage),
            roleId: user.roleId,
            registerTime: user.createdAt,
            lastLogin: user.updatedAt,
          }));
          this.userList = formattedUsers;
          resolve(formattedUsers);
        });
      });
    },

    mapRoleIdToName(roleId) {
      const roleMap = {
        1: "系统管理员",
        2: "培训导师",
        3: "护理学员",
      };
      return roleMap[roleId] || "未知角色";
    },

    mapStageToStatus(stage) {
      const statusMap = {
        // active: "活跃",
        // inactive: "未激活",
        // locked: "已锁定",
        // pending: "待审核",
        intern: "实习",
        formal: "正式"
      };
      return statusMap[stage] || "未知状态";
    },
    async fetchAllPermissions() {
      // 如果已获取，则不重复执行
      if (this.allPermissions.size > 0) return;

      try {
        // 假设后端提供了一个 /api/permission/all 的接口返回所有权限描述的数组
        const response = await new Promise((resolve, reject) => {
          common_util.get("/api/permission", {}, resolve, reject);
        });
        //this.allPermissions = new Set(response); // 将数组转为 Set 存储
        this.allPermissions = new Set(response.map(item => item.description));
      } catch (error) {
        console.error("获取所有可用权限列表失败:", error);
      }
    },
  },
});
